package main

import (
	"flag"
	"fmt"
	"aws_sys_monitor/common"
	"io/ioutil"
	"os/exec"
	"os"
	"strings"
	"strconv"
)

const (
	projectDir  = "/home/simplecredit/project/"
	execUser = "simplecredit"
)

type TomcatMertic struct {
	TomcatName string
	Pid        string
	//[OldSpace,PermSpace,YoungGCCount,YoungGCCountTime,FullGCCount,FullGCCount,FullGCCountTime]
	JvmMetricData []float64
	ThreadsNum float64

}

var (
	jvmMertics []*TomcatMertic
)

func (jvm *TomcatMertic) jvmMonitor() {
	cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("sudo -u %s /usr/local/jdk/bin/jstat -gcutil %s",execUser, jvm.Pid))
	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("查询 %s jvm用量命令失败 %s",jvm.TomcatName,out)
		return
	}

	for _, line := range strings.Split((string(out)), "\n")[1:2] {
		fields := strings.Fields(line)
		Metrics := StringToFloat(fields)

		jvm.JvmMetricData = Metrics[3:9]

		}
}

func (t *TomcatMertic) threadMonitor()  {
	statusLine, err := common.ReadAll(fmt.Sprintf("/proc/%s/status",t.Pid))
	if err != nil {
		fmt.Printf("找不到 %s 项目 %s 的 PID\n",t.TomcatName,t.Pid)
		return
	}
	for _, line := range strings.Split((string(statusLine)), "\n") {
		if strings.HasPrefix(line, "Threads") {
			t.ThreadsNum,_ = strconv.ParseFloat(strings.Fields(line)[1],1)

		}

	}

}



func findTomcatPid() {
	dir, err := ioutil.ReadDir(projectDir)
	if err != nil {
		fmt.Printf("没有目录 %v\n",projectDir)
		return
	}
	for _, fi := range dir {
		pidFile := projectDir + fi.Name() + "/bin/tomcat.pid"
		_, err = os.Stat(pidFile)
		if err == nil {
			pidByte, _ := common.ReadAll(pidFile)
			pid := strings.Trim(string(pidByte), "\n")
			jvmMertic := &TomcatMertic{
				TomcatName: fi.Name(),
				Pid:        pid,
			}
			jvmMertics = append(jvmMertics, jvmMertic)
		} else {
			fmt.Printf("文件不存在 %s\n",err)
		}


	}
}

func StringToFloat(metrics []string) []float64 {
	var toMetrics []float64
	for _, s := range metrics {
		f, _ := strconv.ParseFloat(s, 1)
		toMetrics = append(toMetrics, f)
	}
	return toMetrics
}

func main() {
	flag.Parse()
	findTomcatPid()
	fmt.Println(jvmMertics)
	for _, jvmOb := range jvmMertics {
		jvmOb.jvmMonitor()
		jvmOb.threadMonitor()
		fmt.Println(*jvmOb)
	}

}
